/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.tedu.mall.order.service.impl;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.pojo.order.dto.CartAddDTO;
import cn.tedu.mall.common.pojo.order.dto.CartUpdateDTO;
import cn.tedu.mall.common.pojo.order.model.OmsCart;
import cn.tedu.mall.common.pojo.order.vo.CartStandardVO;
import cn.tedu.mall.common.pojo.product.vo.SkuStandardVO;
import cn.tedu.mall.common.pojo.sso.authentication.CsmallAuthenticationInfo;
import cn.tedu.mall.common.restful.JsonPage;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.order.mapper.OmsCartMapper;
import cn.tedu.mall.order.service.IOmsCartService;
import cn.tedu.mall.product.service.order.IForOrderSkuService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java.util.List;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 购物车数据表 服务实现类
 * </p>
 *
 * @since 2022-02-16
 */
@Service
public class OmsCartServiceImpl implements IOmsCartService {
    @Autowired
    private OmsCartMapper omsCartMapper;
    @DubboReference
    private IForOrderSkuService dubboOrderSkuService;

    @Override
    public void addCart(CartAddDTO cartDTO) throws CoolSharkServiceException {
        //获取userId
        Long userId = getUserId();
        //先检查是否存在cart
        OmsCart omsCartExist = omsCartMapper.selectExistCart(userId, cartDTO.getSkuId());
        if (omsCartExist != null) {
            //说明存在,更新num
            omsCartExist.setQuantity(cartDTO.getQuantity() + omsCartExist.getQuantity());
            //更新数据库
            omsCartMapper.updateQuantityById(omsCartExist);
        } else {
            //调用接口
            SkuStandardVO skuStandardVO = dubboOrderSkuService.getById(cartDTO.getSkuId());
            OmsCart omsCart = new OmsCart();
            BeanUtils.copyProperties(cartDTO, omsCart);
            omsCart.setUserId(userId);
            omsCart.setData(skuStandardVO.getSpecifications());
            omsCart.setBarCode(skuStandardVO.getBarCode());
            omsCartMapper.saveCart(omsCart);
        }
    }

    @Override
    public JsonPage<CartStandardVO> listCarts(Integer page, Integer pageSize) {
        //从security拿到username,dubbo调用微服务获取userInfo
        Long userId = getUserId();
        PageHelper.startPage(page, pageSize);
        List<CartStandardVO> carts = omsCartMapper.selectCartsByUserId(userId);
        return JsonPage.restPage(new PageInfo<>(carts));
    }

    @Override
    public void removeCart(Long[] ids) throws CoolSharkServiceException {
        //获取用户信息
        /*AdminVO userInfo = getUserInfo();
        Long userId=userInfo.getId();*/
        int result = omsCartMapper.deleteCartsByIds(ids);
        if (result == 0) {
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND, "您的购物车没有对应商品");
        }
    }

    @Override
    public void removeAllCarts() throws CoolSharkServiceException {
        //从security框架获取suerId
        Long userId = getUserId();
        int result = omsCartMapper.deleteCartsByUserId(userId);
        if (result == 0) {
            throw new CoolSharkServiceException(ResponseCode.NOT_ACCEPTABLE, "您的购物车没有数据可以清空");
        }
    }

    @Override
    public void updateQuantity(CartUpdateDTO cartUpdateDTO) {
        OmsCart omsCart = new OmsCart();
        BeanUtils.copyProperties(cartUpdateDTO, omsCart);
        omsCartMapper.updateQuantityById(omsCart);
    }

    @Override
    public void removeUserCarts(OmsCart omsCart) {
        omsCartMapper.deleteCartBySkuIdAndUserId(omsCart);
    }

    public CsmallAuthenticationInfo getUserInfo() {
        //从security环境获取username,先拿到authentication
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        //如果不是空的可以调用dubbo远程微服务获取adminVO
        if (authentication != null) {
            CsmallAuthenticationInfo csmallAuthenticationInfo = (CsmallAuthenticationInfo) authentication.getCredentials();
            return csmallAuthenticationInfo;
        } else {
            throw new CoolSharkServiceException(ResponseCode.UNAUTHORIZED, "没有登录者信息");
        }
    }

    public Long getUserId() {
        CsmallAuthenticationInfo userInfo = getUserInfo();
        return userInfo.getId();
    }
}
